package org.yxs.es;

import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.Objects;

/**
 * @author: y-xs
 * @date: 2021/08/25 18:36
 * @description: 文档操作
 */
public class ElasticsearchDocTest {

    /**
     * 连接客户端
     */
    private RestHighLevelClient client;

    @Before
    public void init() {
        HttpHost serverHost = new HttpHost("127.0.0.1", 9200);
        client = new RestHighLevelClient(RestClient.builder(serverHost));
    }

    @After
    public void destroy() {
        if (Objects.nonNull(client)) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建文档
     */
    @Test
    public void testCreate() throws IOException {
        IndexRequest request = new IndexRequest();
        // 指定索引
        request.index("java");
        // 指定id
        request.id("1001");
        // 存储数据
        EsUser user = new EsUser("zhangsan", 30, "男");
        // 指定source内容
        request.source(user.toJsonString(), XContentType.JSON);
        // 请求
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    /**
     * 修改文档
     */
    @Test
    public void testUpdate() throws IOException {
        UpdateRequest request = new UpdateRequest();
        // 指定索引
        request.index("java");
        // 指定id
        request.id("1001");

        // 更新内容
        EsUser user = new EsUser("ES", 18, "女");
        request.doc(user.toJsonString(), XContentType.JSON);

        // ES请求
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    /**
     * 文档查询
     */
    @Test
    public void testQuery() throws IOException {
        GetRequest request = new GetRequest().index("java").id("1001");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println(response.getSource());
    }

    /**
     * 删除文档
     */
    @Test
    public void testDelete() throws IOException {
        DeleteRequest request = new DeleteRequest().index("java").id("1001");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    /**
     * 批量操作，针对于增删改
     */
    @Test
    public void testBatch() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        // 先删除
        bulkRequest.add(new DeleteRequest().index("java").id("1001"));
        // 再添加
        EsUser user = new EsUser("EsJava", 18, "男");
        bulkRequest.add(new IndexRequest().index("java").id("1002").source(user.toJsonString(), XContentType.JSON));

        BulkResponse responses = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(responses);
//        PrintUtil.buttyPrint(responses);
    }

    /**
     * match查询
     */
    @Test
    public void testAdvanceMatchQuery() throws IOException {
        SearchRequest request = new SearchRequest("java");

        // 查询条件构造
        SearchSourceBuilder builder = new SearchSourceBuilder();

        // 匹配查询
        /// QueryBuilders提供命令中的查询匹配关系
        /// 查询所有
        /// QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        /// 单个查询
        /// QueryBuilder queryBuilder = QueryBuilders.matchQuery("age", 18);
        /// 短语匹配查询
        QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery("name", "EsJava");
        builder.query(queryBuilder);

        request.source(builder);
        SearchResponse responses = client.search(request, RequestOptions.DEFAULT);
        System.out.println(responses.getHits());
//        PrintUtil.buttyPrint(responses.getHits());
    }

    /**
     * bool查询
     */
    @Test
    public void testAdvanceBoolQuery() throws IOException {
        SearchRequest request = new SearchRequest("java");

        // 查询条件构造
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        // must
        queryBuilder.must(QueryBuilders.matchQuery("age", 18));
        // mustNot
        queryBuilder.mustNot(QueryBuilders.matchQuery("sex", "女"));
        // should
        queryBuilder.should(QueryBuilders.matchQuery("name", "zhangsan"));

        builder.query(queryBuilder);
        request.source(builder);
        SearchResponse responses = client.search(request, RequestOptions.DEFAULT);
//        PrintUtil.buttyPrint(responses.getHits());
        System.out.println((responses.getHits()));
    }

    /**
     * 分页查询
     */
    @Test
    public void testAdvancePageQuery() throws IOException {
        SearchRequest request = new SearchRequest("java");

        // 查询条件构
        SearchSourceBuilder builder = new SearchSourceBuilder();
        MatchAllQueryBuilder queryBuilder = QueryBuilders.matchAllQuery();

        // query <==> select
        builder.query(queryBuilder);

        // 分页查询
        builder.from(0);
        builder.size(2);

        // 指定排序
        builder.sort("age", SortOrder.ASC);

        request.source(builder);
        SearchResponse responses = client.search(request, RequestOptions.DEFAULT);
        for (SearchHit searchHit : responses.getHits()) {
            System.out.println(searchHit.getSourceAsString());
        }
    }

    /**
     * 高亮查询
     */
    @Test
    public void testAdvanceHighLightQuery() throws IOException {
        SearchRequest request = new SearchRequest("java");

        // 查询条件构
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 注意高亮全部查询时无意义
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("name", "java");
        builder.query(queryBuilder);

        // 高亮搜搜，和查询同级
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("name");

        builder.highlighter(highlightBuilder);
        request.source(builder);
        SearchResponse responses = client.search(request, RequestOptions.DEFAULT);
        for (SearchHit searchHit : responses.getHits()) {
            System.out.println(searchHit.getHighlightFields());
        }
    }

}
